/**
 * 全局可复用的自定义hooks
 */
import type { FollowType } from '@/types/consult'
import { followDoctor } from '@/api/consult'
import { ref, watch, onMounted } from 'vue'
import { useClipboard } from '@vueuse/core'
import { getPrescriptionPic } from '@/api/consult'
import { showImagePreview, showFailToast, showSuccessToast } from 'vant'
import { getMedicalOrderDetail } from '@/api/medicine'
import type { OrderDetail } from '@/types/medicine'
// 关注医生或文章
const useFollow = (type: FollowType = 'doc') => {
  // 关注医生逻辑
  const loading = ref(false)
  const follow = async (doc: { id: string; likeFlag: 0 | 1 }) => {
    // 防止重复点击
    loading.value = true
    try {
      await followDoctor(doc.id, type)
      doc.likeFlag = doc.likeFlag === 1 ? 0 : 1
    } finally {
      // 无论 try / catch 结果如何都会执行的代码块
      loading.value = false
    }
  }
  return { useFollow, loading, follow }
}
// 查看处方
const useShowPrescription = () => {
  const showPrescription = async (id?: string) => {
    if (id) {
      const res = await getPrescriptionPic(id)
      console.log('=处方图片预览', res)
      showImagePreview([res.data.url])
    }
  }
  return { showPrescription }
}

// 复制
const useCopy = () => {
  const { copy, copied, isSupported } = useClipboard()
  // 1. 复制回调
  const onCopy = (copyText: string) => {
    if (!copyText) showFailToast('没有订单号')
    if (!isSupported.value) showFailToast('未授权，不支持')
    copy(copyText)
  }
  // 2. 复制后提示
  watch(copied, () => {
    if (copied.value) showSuccessToast('已复制')
  })
  return {
    onCopy
  }
}

// 药品订单详情
const useMedicineDetail = (id: string) => {
  const order = ref<OrderDetail>()
  onMounted(async () => {
    const { data } = await getMedicalOrderDetail(id)
    console.log('=支付结果', data)

    order.value = data
  })
  return { order }
}

export { useFollow, useShowPrescription, useCopy, useMedicineDetail }
